Python Keywords: An Introduction – Real Python

您所在的位置:网站首页 reserved word in python Python Keywords: An Introduction – Real Python

Python Keywords: An Introduction – Real Python

2023-03-12 08:38| 来源: 网络整理| 查看: 265

The else Keyword Used With Loops

In addition to using the else keyword with conditional if statements, you can also use it as part of a loop. When used with a loop, the else keyword specifies code that should be run if the loop exits normally, meaning break was not called to exit the loop early.

The syntax for using else with a for loop looks like the following:

for in : else:

This is very similar to using else with an if statement. Using else with a while loop looks similar:

while : else:

The Python standard documentation has a section on using break and else with a for loop that you should really check out. It uses a great example to illustrate the usefulness of the else block.

The task it shows is looping over the numbers two through nine to find the prime numbers. One way you could do this is with a standard for loop with a flag variable:

>>>>>> for n in range(2, 10): ... prime = True ... for x in range(2, n): ... if n % x == 0: ... prime = False ... print(f"{n} is not prime") ... break ... if prime: ... print(f"{n} is prime!") ... 2 is prime! 3 is prime! 4 is not prime 5 is prime! 6 is not prime 7 is prime! 8 is not prime 9 is not prime

You can use the prime flag to indicate how the loop was exited. If it exited normally, then the prime flag stays True. If it exited with break, then the prime flag will be set to False. Once outside the inner for loop, you can check the flag to determine if prime is True and, if so, print that the number is prime.

The else block provides more straightforward syntax. If you find yourself having to set a flag in a loop, then consider the next example as a way to potentially simplify your code:

>>>>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(f"{n} is not prime") ... break ... else: ... print(f"{n} is prime!") ... 2 is prime! 3 is prime! 4 is not prime 5 is prime! 6 is not prime 7 is prime! 8 is not prime 9 is not prime

The only thing that you need to do to use the else block in this example is to remove the prime flag and replace the final if statement with the else block. This ends up producing the same result as the example before, only with clearer code.

Sometimes using an else keyword with a loop can seem a little strange, but once you understand that it allows you to avoid using flags in your loops, it can be a powerful tool.

Remove ads


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3